package com.thz.common.utils;

import jakarta.servlet.http.HttpServletRequest;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

/**
 * IP工具类
 * 
 * @author THZ
 * @date 2025
 */
public class IpUtils {
    
    /**
     * 获取客户端真实IP地址
     * 如果是本地回环地址，则获取本机的真实IP地址
     * 
     * @param request HTTP请求对象
     * @return IP地址
     */
    public static String getClientIp(HttpServletRequest request) {
        if (request == null) {
            return "unknown";
        }
        
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        
        // 对于通过多个代理的情况，第一个IP为客户端真实IP
        if (ip != null && ip.contains(",")) {
            ip = ip.split(",")[0].trim();
        }
        
        // 如果是本地回环地址，获取本机真实IP
        if (isLocalhost(ip)) {
            ip = getLocalRealIp();
        }
        
        return ip != null ? ip : "unknown";
    }
    
    /**
     * 判断是否为本地回环地址
     * 
     * @param ip IP地址
     * @return 是否为本地回环地址
     */
    private static boolean isLocalhost(String ip) {
        if (ip == null || ip.isEmpty()) {
            return false;
        }
        // IPv4回环地址
        if (ip.equals("127.0.0.1") || ip.equals("localhost")) {
            return true;
        }
        // IPv6回环地址
        if (ip.equals("0:0:0:0:0:0:0:1") || ip.equals("::1")) {
            return true;
        }
        return false;
    }
    
    /**
     * 获取本机真实IP地址
     * 优先返回IPv4地址，如果没有则返回IPv6地址
     * 
     * @return 本机真实IP地址
     */
    private static String getLocalRealIp() {
        try {
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            String ipv4Address = null;
            String ipv6Address = null;
            
            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = networkInterfaces.nextElement();
                
                // 跳过回环接口和未启用的接口
                if (networkInterface.isLoopback() || !networkInterface.isUp()) {
                    continue;
                }
                
                Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
                while (inetAddresses.hasMoreElements()) {
                    InetAddress inetAddress = inetAddresses.nextElement();
                    
                    // 跳过回环地址
                    if (inetAddress.isLoopbackAddress()) {
                        continue;
                    }
                    
                    // 跳过链路本地地址（fe80::开头）
                    String hostAddress = inetAddress.getHostAddress();
                    if (hostAddress.startsWith("fe80:") || hostAddress.startsWith("169.254.")) {
                        continue;
                    }
                    
                    // 优先保存IPv4地址
                    if (inetAddress.getAddress().length == 4) {
                        ipv4Address = hostAddress;
                        break; // 找到IPv4地址就退出
                    } else if (ipv6Address == null) {
                        // 保存第一个非回环的IPv6地址
                        ipv6Address = hostAddress;
                    }
                }
                
                // 如果已经找到IPv4地址，就不继续查找了
                if (ipv4Address != null) {
                    break;
                }
            }
            
            // 优先返回IPv4地址
            if (ipv4Address != null) {
                return ipv4Address;
            }
            
            // 如果没有IPv4，返回IPv6
            if (ipv6Address != null) {
                return ipv6Address;
            }
            
            // 如果都没有找到，返回本机IP（可能是127.0.0.1的别名）
            InetAddress localHost = InetAddress.getLocalHost();
            return localHost.getHostAddress();
            
        } catch (Exception e) {
            // 如果获取失败，返回默认值
            return "127.0.0.1";
        }
    }
}




